from django.shortcuts import render, HttpResponse
from django import forms
from web.models import *
from web.Tools import PublicFn
import json

# 公用函数
YYPublicFn = PublicFn.YYPublicTools_Class()


# 首页
def view_index(request):
    if request.method == 'GET':
        return render(request, '后台-首页.html')


class store(forms.ModelForm):
    class Meta:
        model = vendors
        fields = '__all__'
        error_messages = {
            "name": {
                "required": "请输入商家名称"
            },
            "vendorsPhone": {
                "required": "请输入电话"
            },
        }


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "12345"}



# 商店 - 创建商店
def view_create_store(request):
    if request.method == 'GET':
        form = store()
        return render(request, '创建商店.html', {"form": form})
    elif request.method == 'POST':
        data = YYPublicFn.GetKey(request.POST)
        form = store(data=data)
        if form.is_valid():
            form.save()
            row_obj = vendors.objects.filter(name=data['name']).first()
            result = {
                "id": row_obj.id,
                "name": row_obj.name
            }
            return HttpResponse(json.dumps(result))
        else:
            errorTest = "失败原因: <br>"
            for field, errors in form.errors.items():
                for error in errors:
                    errorTest += f"<span style='margin:0 10px;'>报错字段: {field}  报错原因: <i style='color:red;'>{error}</i></span>"
            return HttpResponse(errorTest, status=400)


# 商店 - 创建商品导航
class create_nav(forms.ModelForm):
    vendors_id = forms.ModelChoiceField(
        queryset=vendors.objects.all(),
        label='关联商家',
        empty_label='选择一个商家',
        widget=forms.Select(attrs={'class': 'layui-input'})
    )

    class Meta:
        model = VendorGoodsNavigator
        fields = ['vendors_id', 'name']
        error_messages = {
            "name": {
                "required": "请输入导航名称"
            }
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "layui-input"}


# 商店 - 创建商品导航
def view_create_nav(request):
    if request.method == 'GET':
        form = create_nav()
        return render(request, '创建商品导航.html', {"form": form})
    elif request.method == 'POST':
        data = YYPublicFn.GetKey(data=request.POST, index=0)

        form = create_nav(data=data)
        if form.is_valid():
            form.save()
            return HttpResponse("<span>创建成功</span>")
        else:
            errorTest = "失败原因: <br>"
            for field, errors in form.errors.items():
                for error in errors:
                    errorTest += f"<span style='margin:0 10px;'>报错字段: {field}  报错原因: <i style='color:red;'>{error}</i></span>"
            return HttpResponse(errorTest, status=400)


# 商店 - 创建商品
class create_products(forms.ModelForm):
    class Meta:
        model = products
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "layui-input"}


# 商店 - 创建商品
def view_create_products(request):
    if request.method == 'GET':
        # 获取全部商家
        store_all = vendors.objects.all()
        # 商品唯一标识码
        sku = YYPublicFn.Response_Number()
        return render(request, '创建商品.html', {"store_all": store_all, "sku": sku})
    elif request.method == 'POST':
        data = YYPublicFn.GetKey(request.POST)
        form = create_products(data=data)
        if form.is_valid():
            form.save()
            sku = YYPublicFn.Response_Number()
            result = {
                "sku": sku,
                "name": data['name'],
                "id": data['VendorGoodsNavigator_id']
            }
            return HttpResponse(json.dumps(result))
        else:
            errorTest = "失败原因: <br>"
            for field, errors in form.errors.items():
                for error in errors:
                    errorTest += f"<span style='margin:0 10px;'>报错字段: {field}  报错原因: <i style='color:red;'>{error}</i></span>"
            return HttpResponse(errorTest, status=400)
